package com.google.android.daca;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.Toast;
import android.widget.LinearLayout.LayoutParams;

import com.google.android.daca.exceptions.AuthenticationErrorException;
import com.google.android.daca.exceptions.BadRequestException;
import com.google.android.daca.exceptions.ColumnConstraintExceededException;
import com.google.android.daca.exceptions.InvalidResponseCodeException;
import com.google.android.daca.exceptions.ParticipantAlreadyExistsException;
import com.google.android.daca.exceptions.ParticipantIDNotReturnedException;
import com.google.android.daca.exceptions.RowConstraintExceededException;
import com.google.android.daca.service.DoodleRESTService;
import com.google.android.daca.types.Option;
import com.google.android.daca.types.Participant;
import com.google.android.daca.types.Poll;

/**
 * Activity used to show poll details.
 * 
 * @author ivo
 */
public class PollActivity extends ListActivity 
{
    private static final String CLASS_TAG = DACAConstants.APP_LOG_TAG + " " + PollActivity.class.getSimpleName();
	private static String[] optionsArray;

	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		
		final Bundle bundle = getIntent().getExtras();
		final Poll poll = bundle.getParcelable(getResources().getString(R.string.extra_poll_object));
		prepareOptions(poll);

		setListAdapter(new ArrayAdapter<String>(this,
		                                        android.R.layout.simple_list_item_multiple_choice,
		                                        getOptionsArray()));

		final ListView listView = getListView();
		listView.setItemsCanFocus(false);
		listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

		Button btn = new Button(this);
		btn.setText("Vote");
		btn.setOnClickListener(new OnClickListener() 
		{
			@Override
			public void onClick(View v) 
			{
				final DoodleRESTService dRs = new DoodleRESTService();
				SparseBooleanArray checked = listView.getCheckedItemPositions();
				Participant participant = new Participant();
				participant.setName((String) bundle.get(getResources().getString(R.string.extra_doodle_name)));
				List<Integer> preferences = new ArrayList<Integer>();
				for (int i = 0; i < optionsArray.length; ++i) 
				{
					if (checked.get(i, false)) 
					{
						preferences.add(1);
					} 
					else 
					{
						preferences.add(0);
					}
				}
				participant.setPreferences(preferences);
				try
				{
					dRs.participate(participant, poll.getPollID());
					Toast.makeText(getApplicationContext(),
					               "You succesfully voted", Toast.LENGTH_LONG).show();
				} 
				catch (ParticipantAlreadyExistsException pae)
				{
                    Toast.makeText(getApplicationContext(),
                                   pae.getMessage(),
                                   Toast.LENGTH_LONG)
                                   .show();
                    Log.e(CLASS_TAG + " onCreate", pae.getMessage());
                }
                catch (RowConstraintExceededException rce)
                {
                    Toast.makeText(getApplicationContext(),
                                   rce.getMessage(),
                                   Toast.LENGTH_LONG)
                                   .show();
                    Log.e(CLASS_TAG + " onCreate", rce.getMessage());
                }
                catch (ColumnConstraintExceededException cce)
                {
                    Toast.makeText(getApplicationContext(),
                                   cce.getMessage(),
                                   Toast.LENGTH_LONG)
                                   .show();
                    Log.e(CLASS_TAG + " onCreate", cce.getMessage());
                }
                catch (ParticipantIDNotReturnedException pnre)
                {
                    Toast.makeText(getApplicationContext(),
                                    pnre.getMessage(),
                                   Toast.LENGTH_LONG)
                                   .show();
                    Log.e(CLASS_TAG + " onCreate", pnre.getMessage());
                }
                catch (InvalidResponseCodeException irce)
                {
                    Toast.makeText(getApplicationContext(),
                                   irce.getMessage(),
                                   Toast.LENGTH_LONG)
                                   .show();
                    Log.e(CLASS_TAG + " onCreate", irce.getMessage());
                }
                catch (AuthenticationErrorException aee)
                {
                    Toast.makeText(getApplicationContext(),
                                   aee.getMessage(),
                                   Toast.LENGTH_LONG)
                                   .show();
                    Log.e(CLASS_TAG + " onCreate", aee.getMessage());
                }
                catch (BadRequestException bre) 
                {
                    Toast.makeText(getApplicationContext(),
                                   bre.getMessage(),
                                   Toast.LENGTH_LONG)
                                   .show();
                    Log.e(CLASS_TAG + " onCreate", bre.getMessage());
                }
                catch (IOException ioe) 
                {
                    Toast.makeText(getApplicationContext(),
                                   "Communication error occurred, try again.",
                                   Toast.LENGTH_LONG)
                                   .show();
                    Log.e(CLASS_TAG + " onCreate", ioe.getMessage());
                }
			}
		});
		ScrollView.LayoutParams layoutOpt = new ScrollView.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		layoutOpt.gravity = Gravity.BOTTOM;
		this.addContentView(btn, layoutOpt);
	}

	/**
	 * Helper method to prepare the poll options.
	 * 
	 * @param poll
	 */
	private void prepareOptions(Poll poll)
	{
		List<Option> pollOptions = poll.getOptions();
		setOptionsArray(new String[pollOptions.size()]);
		int i = 0;
		for (Option option : pollOptions) 
		{
			getOptionsArray()[i] = option.getValue();
			i++;
		}
		Log.i(CLASS_TAG, "num options is: " + getOptionsArray().length);
	}

	/**
	 * Returns the options array.
	 * 
	 * @return
	 */
	public static String[] getOptionsArray() 
	{
		return optionsArray;
	}
	
	/**
	 * Sets the options array.
	 * 
	 * @param optionsArray
	 */
	public static void setOptionsArray(String[] optionsArray) 
	{
		PollActivity.optionsArray = optionsArray;
	}
}
